package com.saturday.web.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Map;

public class WebUtils {

    private static final Logger logger = LoggerFactory.getLogger(WebUtils.class);

    public static void resp(HttpServletResponse response, Object result) {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try (OutputStream out = response.getOutputStream()) {
            out.write(JSONObject.toJSONString(result).getBytes());
            out.flush();
        } catch (IOException e) {
            logger.error("系统异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取content-type=application/json类型请求参数
     * @param request
     * @return
     */
    public static String getRequestBodyToStr(HttpServletRequest request) {
        String contentType = request.getContentType();
        if (StringUtils.isNotBlank(contentType) && !contentType.toLowerCase().startsWith(MediaType.APPLICATION_JSON_VALUE)) {
            logger.info("content-type != application/json");
            return null;
        }
        String charset = request.getCharacterEncoding();
        try(InputStream in = request.getInputStream()) {
            return StreamUtils.copyToString(in, Charset.forName(charset));
        } catch (IOException e) {
            logger.error("获取content-type=application/json类型请求参数异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取请求入参
     * @param request
     * @return JSONString
     */
    public static JSONObject getRequestParamsToJSON(HttpServletRequest request) {
        String contentType = request.getContentType();
        if (StringUtils.isNotBlank(contentType) && request.getContentType().toLowerCase().startsWith(MediaType.APPLICATION_JSON_VALUE)) {
            String params = getRequestBodyToStr(request);
            return JSONObject.parseObject(params);
        }
        JSONObject obj = new JSONObject();
        for(Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            obj.put(entry.getKey(), entry.getValue().length == 1 ? entry.getValue()[0] : entry.getValue());
        }
        return obj;
    }

    /**
     * 获取content-type=application/json类型请求参数
     * @param request
     * @return
     */
    public static byte[] getRequestBodyToByteArr(HttpServletRequest request) {
        String responseStr = getRequestBodyToStr(request);
        if(null != responseStr) {
            return responseStr.getBytes();
        }
        return null;
    }

    /**
     * 获取cookies
     * @param request
     * @param name cookies名称
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Assert.notNull(request, "Request must not be null");
        Assert.notNull(name, "cookies name must not be null");
        Cookie[] cookies = request.getCookies();
        if (null == cookies) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie;
            }
        }
        return null;
    }

}
